package main

import (
	"context"
	"fmt"
	"time"

	"go.etcd.io/etcd/client/v3"
)

// Lease
func main() {

	cfg := clientv3.Config{
		Endpoints: []string{"192.168.0.121:2379"},

		DialTimeout: 5 * time.Second,
	}

	client, err := clientv3.New(cfg)
	if err != nil {
		fmt.Println(err)
		return
	}

	lease := clientv3.NewLease(client)
	// 10s租约
	grant, err := lease.Grant(context.TODO(), 10)
	if err != nil {
		fmt.Println(err)
		return
	}
	leaseId := grant.ID
	// 自动续租 10s，永不过期
	//aliveChan, err := lease.KeepAlive(context.TODO(), leaseId)

	// 15s租期
	ctx, _ := context.WithTimeout(context.TODO(), 5*time.Second)
	aliveChan, err := lease.KeepAlive(ctx, leaseId)
	if err != nil {
		fmt.Println(err)
		return
	}
	go func() {
		for {
			select {
			case keepResp := <-aliveChan:
				// channel关闭：超时，主动取消，续租失败等等原因
				if keepResp == nil {
					fmt.Println("租约已经失效")
					return
				} else {
					fmt.Println("收到自动续租应答", keepResp.ID)
				}
			}
		}
	}()

	kv := clientv3.NewKV(client)
	_, err = kv.Put(context.TODO(), "/cron/lock/job1", "", clientv3.WithLease(leaseId))
	if err != nil {
		fmt.Println(err)
		return
	}

	for true {
		getResp, err := kv.Get(context.TODO(), "/cron/lock/job1")
		if err != nil {
			fmt.Println(err)
			return
		}
		if getResp.Count == 0 {
			fmt.Println("kv过期了")
			break
		}
		fmt.Println(getResp.Kvs)
		time.Sleep(2 * time.Second)
	}

}
